package com.inspur.icity.bus.base.core.web;

import com.inspur.icity.bus.base.core.builder.ToMapBuilder;
import com.inspur.icity.bus.base.core.service.CrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


public class CrudController<Service extends CrudService, M, PK> extends BaseController {

    @Autowired
    protected Service crudService;
    protected ToMapBuilder<M> toMapBuilder;


    @ResponseBody
    @RequestMapping(value = "/{id}")
    public Object get(@PathVariable PK id) {
        return toMapBuilder.build((M)crudService.get(id));
    }

    @ResponseBody
    @RequestMapping
    public Object find() {
        return map(crudService.find(getPageBounds()), m -> {
            return toMapBuilder.build((M)m);
        });
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public void add(@RequestBody M m) {
        crudService.add(m);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.PUT)
    public void update(@RequestBody M m) {
        crudService.update(m);
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void remove(@PathVariable PK id) {
        crudService.remove(id);
    }
}
